package com.hrma.controller;

import com.github.pagehelper.Page;
import com.hrma.entity.ListWithCount;
import com.hrma.entity.Post;
import com.hrma.entity.PostDTO;
import com.hrma.entity.SelectResult;
import com.hrma.services.PostService;
import com.hrma.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/post")
@Slf4j
public class PostController {
    @Autowired
    private final PostService postService;

    public PostController(PostService postService) {
        this.postService = postService;
    }

    @PostMapping("/add")
    public Result<Post> addPost(@Validated @RequestBody Post data) {
        log.debug("收到add请求，请求参数：{}", data);
        return Result.ok(postService.addPost(data));
    }

    @DeleteMapping("/delete/{id}")
    public Result<?> deletePost(@PathVariable int id) {
        log.debug("收到delete请求，请求参数：{}", id);
        postService.deletePost(id);
        return Result.ok(null);
    }

    @PatchMapping("/update")
    public Result<?> updatePost(@Validated @RequestBody Post data) {
        log.debug("收到update请求，请求参数：{}", data);
        postService.updatePost(data);
        return Result.ok(null);
    }

    @GetMapping("/select")
    public Result<List<SelectResult>> select() {
        log.debug("收到select请求！");
        return Result.ok(postService.select());

    }

    @PostMapping("/list")
    public Result<ListWithCount<Post>> getList(@RequestBody PostDTO data) {
        log.debug("收到list请求，请求参数：{}", data);
        Page<Post> res = postService.getList(data);

        return Result.ok(new ListWithCount<>(res.getTotal(), res));
    }
}
